import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';

import 'at_auth_plugin_platform_interface.dart';

class MethodChannelAtAuthPlugin extends AtAuthPluginPlatform {
  @visibleForTesting
  final methodChannel = const MethodChannel('at_auth_plugin/method');
  final eventChannel = const EventChannel('at_auth_plugin/event');

  /// 🔹 缓存事件流，防止重复订阅
  Stream<Map<String, dynamic>>? _loginStream;

  @override
  Future<Map<String, dynamic>> setAuthSDKInfo(String appSecret) async {
    final result = await methodChannel.invokeMethod('setAuthSDKInfo', {
      'appSecret': appSecret,
    });
    return Map<String, dynamic>.from(result);
  }

  @override
  Future<String> getVersion() async {
    final version = await methodChannel.invokeMethod<String>('getSDKVersion');
    return version ?? 'unknown';
  }

  @override
  Future<Map<String, dynamic>> getLoginToken() async {
    final raw = await methodChannel.invokeMethod<Map>('getLoginToken') as Map?;
    if (raw == null) return {'status': 'error', 'message': 'no response'};
    return Map<String, dynamic>.from(raw);
  }

  /// 🔹 新增：EventChannel 登录事件流
  @override
  Stream<Map<String, dynamic>> get loginStream {
    _loginStream ??= eventChannel
        .receiveBroadcastStream()
        .map((event) => Map<String, dynamic>.from(event))
        .distinct((prev, next) => mapEquals(prev, next));
    return _loginStream!;
  }
}
